<?php

namespace Admin\Models\hrm;

use Admin\Models\BaseModel;
use Admin\Models\user\XhsysUser;
use Helpers\Excel;
use Helpers\Main;
use Helpers\Tool;
use Phalcon\Di;
use Services\HundredMail;

class XhhrmStaff extends BaseModel
{

    /**
     *
     * @var integer
     * @Primary
     * @Identity
     * @Column(type="integer", length=11, nullable=false)
     */
    public $iStaffId;

    public $sChargeDeps;

    /**
     * @var int
     * @Column(type="integer", length=11, nullable=true)
     */
    public $iStaffStatus;

    /**
     * @var int
     * @Column(type="integer", length=11, nullable=true)
     */
    public $iOfferStatus;

    /**
     * @var int
     * @Column(type="integer", length=11, nullable=true)
     */
    public $iStaffLevel;

    /**
     *
     * @var integer
     * @Column(type="integer", length=11, nullable=true)
     */
    public $iUserId;

    /**
     *
     * @var string
     * @Column(type="string", length=100, nullable=true)
     */
    public $sStaffName;

    /**
     *
     * @var string
     * @Column(type="string", length=255, nullable=true)
     */
    public $sDepIds;

    /**
     *
     * @var string
     * @Column(type="string", nullable=true)
     */
    public $tBirthday;

    /**
     *
     * @var string
     * @Column(type="string", length=100, nullable=true)
     */
    public $sPrIcon;

    /**
     *
     * @var integer
     * @Column(type="integer", length=1, nullable=true)
     */
    public $iUserSex;

    /**
     *
     * @var string
     * @Column(type="string", length=50, nullable=true)
     */
    public $sBankCard;

    /**
     *
     * @var integer
     * @Column(type="integer", length=1, nullable=true)
     */
    public $bMarried;

    /**
     *
     * @var string
     * @Column(type="string", length=50, nullable=true)
     */
    public $sNationName;

    /**
     *
     * @var string
     * @Column(type="string", length=20, nullable=true)
     */
    public $sNativePlace;

    /**
     *
     * @var string
     * @Column(type="string", length=20, nullable=true)
     */
    public $sIdentityCode;

    /**
     *
     * @var string
     * @Column(type="string", nullable=true)
     */
    public $tStartWork;

    /**
     *
     * @var string
     * @Column(type="string", nullable=true)
     */
    public $tRegularDate;

    /**
     *
     * @var string
     * @Column(type="string", nullable=true)
     */
    public $tHireDate;

    /**
     *
     * @var string
     * @Column(type="string", length=50, nullable=true)
     */
    public $sContractStatus;

    /**
     *
     * @var string
     * @Column(type="string", nullable=true)
     */
    public $sContentDate;

    /**
     *
     * @var integer
     * @Column(type="integer", length=4, nullable=true)
     */
    public $iSignNumber;

    /**
     *
     * @var string
     * @Column(type="string", length=255, nullable=true)
     */
    public $sPostLevel;

    /**
     *
     * @var string
     * @Column(type="string", length=50, nullable=true)
     */
    public $sPostName;

    /**
     *
     * @var string
     * @Column(type="string", nullable=true)
     */
    public $tSocialPayDate;

    /**
     *
     * @var string
     * @Column(type="string", length=50, nullable=true)
     */
    public $sSocialPayStatus;

    /**
     *
     * @var integer
     * @Column(type="integer", length=4, nullable=true)
     */
    public $bInHoliday;

    /**
     *
     * @var integer
     * @Column(type="integer", length=11, nullable=true)
     */
    public $iWorkStatus;

    /**
     *
     * @var string
     * @Column(type="string", nullable=true)
     */
    public $tGraduateDate;

    /**
     *
     * @var string
     * @Column(type="string", length=50, nullable=true)
     */
    public $sProfession;

    /**
     *
     * @var string
     * @Column(type="string", length=100, nullable=true)
     */
    public $sGraduateSchool;

    /**
     *
     * @var string
     * @Column(type="string", length=20, nullable=true)
     */
    public $sCultureLevel;

    /**
     *
     * @var string
     * @Column(type="string", nullable=true)
     */
    public $sSurplusPayStatus;

    /**
     *
     * @var string
     * @Column(type="string", length=20, nullable=true)
     */
    public $sSelfPhone;

    /**
     *
     * @var string
     * @Column(type="string", length=20, nullable=true)
     */
    public $sContractName;

    /**
     *
     * @var string
     * @Column(type="string", length=20, nullable=true)
     */
    public $sContractRelation;

    /**
     *
     * @var string
     * @Column(type="string", length=20, nullable=true)
     */
    public $sContractPhone;

    /**
     *
     * @var string
     * @Column(type="string", length=255, nullable=true)
     */
    public $sFamilyAddress;

    /**
     *
     * @var string
     * @Column(type="string", length=255, nullable=true)
     */
    public $sNowAddress;

    /**
     *
     * @var integer
     * @Column(type="integer", length=20, nullable=true)
     */
    public $sQQNum;

    /**
     *
     * @var string
     * @Column(type="string", length=255, nullable=true)
     */
    public $sWeChatNum;

    /**
     *
     * @var string
     * @Column(type="string", length=50, nullable=true)
     */
    public $sEmailAddress;

    /**
     *
     * @var string
     * @Column(type="string", length=255, nullable=true)
     */
    public $sRemark;

    /**
     *
     * @var integer
     * @Column(type="integer", length=4, nullable=true)
     */
    public $bDelete;

    /**
     *
     * @var string
     * @Column(type="string", nullable=true)
     */
    public $tCreateDate;

    /**
     *
     * @var string
     * @Column(type="string", length=11, nullable=true)
     */
    public $iCreateUserId;

    /**
     *
     * @var string
     * @Column(type="string", nullable=true)
     */
    public $tLastModifyDate;

    /**
     *
     * @var string
     * @Column(type="string", length=11, nullable=true)
     */
    public $iLastModifyUserId;


    /**
     * 离职时间
     *
     * @var string
     * create by xjq 20180620
     */
    public $tLeaveTime;

    /**
     * 退休时间
     *
     * @var string
     * create by xjq 20180620
     */
    public $tRetireTime;

    /**
     * @var integer
     *
     */
    public $iEmploySource;

    /**
     * @var integer
     *
     */
    public $iRecStaff;

    /**
     * @var string
     *
     */
    public $sMaxHire;

    /**
     * @var integer
     */
    public $bCarPlate;

    /**
     * @var string
     */
    public $sUseCar;

    /**
     * @var integer
     */
    public $bEvection;

    /**
     * @var string
     */
    public $mHealth;

    /**
     * @var string
     */
    public $mEvaluate;

    /**
     * @var integer
     */
    public $iCarVeteran;
    /**
     * @var string
     */
    public $sCurMoSalary;
    /**
     * @var string
     */
    public $sCurYeSalary;
    /**
     * @var string
     */
    public $sHpMoSalary;
    /**
     * @var string
     */
    public $sHpYeSalary;

    /**
     * @var string
     */
    public $sProbationSalary;

    /**
     * @var string
     */
    public $sRegularSalary;

    /**
     * @var integer
     */
    public $iRegisterType;

    /**
     * @var string
     */
    public $sProbationDate;

    /**
     * @var integer
     */
    public $iSourceId;

    /**
     * @var string
     */
    public $mHistory;

    /**
     * @var string
     */
    public $sHundredMail;

    /**
     * @var string
     */
    public $sCreateMode;

    /**
     * @var string
     * create by dale 20181031
     */
    public $mSignature;

    /**
     * @var string
     * create by dale 20181109
     */
    public $mToken;

    /**
     * 职工工号
     * @var string
     * create by dale 20181210
     */
    public $sStaffNumber;

    /**
     * 公积金缴纳月份
     *
     * @var string
     * create by dale 20190215
     */
    public $sSurplusPayDate;


    /**
     * 公积金基数
     *
     * @var string
     * create by dale 20190215
     */
    public $sSurplusPayRate;

    /**
     * 意外险缴纳时间
     *
     * @var string
     * create by dale 20190215
     */
    public $sInsuranceDate;

    /**
     * 政治面貌
     *
     * @var string
     * create by dale 20190215
     */
    public $sPoliticsStatus;

    /**
     * 支行信息
     *
     * @var string
     * create by dale 20190215
     *
     */
    public $sBankInfo;

    /**
     * 离职理由
     * @var string
     * create by dale 20190221
     */
    public $sLeaveReason;

    /**
     * 社保开始缴纳月份
     *
     * @var string
     * create by dale 20190221
     */
    public $sSocialPayDate;

    /**
     * 是否特殊账号
     * @var integer
     *
     * create by dale 20190221
     */
    public $bSpecial;



    public static $convertTitleArr = [
        'sDepName' => '部门',
        'sStaffName' => '姓名',
        'sPostName' => '职务岗位',
        'sIdentityCode' => '身份证号码',
        'sSelfPhone' => '联系电话',
        'tHireDate' => '入职日期',
        'tRegularDate' => '转正日期',
        'sProbationDate' => '试用期',
        'iOfferStatus' => '身份类别',
        'iWorkStatus' => '员工分组',
        'iUserSex' => '性别',
//        'tBirthday' => '出生日期',
        'sFamilyAddress' => '户籍地址',
        'iRegisterType' => '户籍性质',
        'sNowAddress' => '现居住家庭住址',
        'sPoliticsStatus' => '政治面貌',
        'sNationName' => '民族',
        'sNativePlace' => '籍贯',
        'sCultureLevel' => '最高学历',
        'sGraduateSchool' => '毕业院校',
        'sProfession' => '专业',
        'sPostLevel' => '职称',
        'tStartWork' => '参加工作时间',
        'sContentDate' => '合同期限',
        'iSignNumber' => '签订次数',
        'sContractStatus' => '合同领用情况',
        'sSocialPayDate' => '社保缴纳开始月份',
        'sSocialPayStatus' => '社保缴纳情况',
        'sSurplusPayDate' => '公积金缴纳月份',
        'sSurplusPayRate' => '公积金缴存基数',
        'sSurplusPayStatus' => '公积金缴纳情况',
        'sInsuranceDate' => '意外险缴纳时间',
        'sBankCard' => '招商银行卡号',
        'sBankInfo' => '支行信息',
        'sContractName' => '紧急联络人',
        'sContractRelation' => '与本人关系',
        'sContractPhone' => '联系人电话',
        'bMarried' => '婚否',
        'sRemark' => '备注'
    ];


    /**
     * Initialize method for model.
     */
    public function initialize()
    {
        parent::initialize();
        $this->keepSnapshots(true);
        $this->setSource("XHHrm_Staff");
    }

    /**
     * Returns table name mapped in the model.
     *
     * @return string
     */
    public function getSource()
    {
        return 'XHHrm_Staff';
    }



    /**
     * 取值时处理
     *
     * created by dale 20171211
     */
    public function afterFetch()
    {
        $monthArr = ['tStartWork', 'tGraduateDate'];
        foreach ($monthArr as $field) {
            if ($this->$field == '0000-00-00') {
                $this->$field = date('Y-m', strtotime(''));
            } else {
                $this->$field = date('Y-m', strtotime($this->$field));
            }
            $this->$field = $this->$field == '1970-01' ? '' :$this->$field;
        }
        $dateArr = ['tHireDate', 'tRegularDate','tLeaveTime','tBirthday', 'tRetireTime'];
        foreach ($dateArr as $field) {
            if ($this->$field == '0000-00-00') {
                $this->$field = date('Y-m-d', strtotime(''));
            } else {
                $this->$field = date('Y-m-d', strtotime($this->$field));
            }
            $this->$field = $this->$field == '1970-01-01' ? '' :$this->$field;
        }
//        $this->tHireDate = date('Y-m', strtotime($this->tHireDate));
//        $this->tRegularDate = date('Y-m', strtotime($this->tRegularDate));
//        $this->tSocialPayDate = date('Y-m', strtotime($this->tSocialPayDate));
//        $this->tStartWork = date('Y-m', strtotime($this->tStartWork));
//        $this->tGraduateDate = date('Y-m', strtotime($this->tGraduateDate));
        return true;
    }

    /**
     * 创建
     *
     * @return bool
     *
     * create by dale  20181016
     */
    public function beforeSave()
    {
        $arr = ['tHireDate','tRegularDate', 'tSocialPayDate', 'tStartWork', 'tGraduateDate', 'tLeaveTime', 'tBirthday', 'tRetireTime'];
        foreach ($arr as $field) {
            if ($this->$field == '0000-00-00') {
                $this->$field = date('Y-m-d', strtotime(''));
            } else {
                $this->$field = date('Y-m-d', strtotime($this->$field));
            }
        }
        return true;
    }


    public function save($data = null, $whiteList = null, $recordUpdateInfo = true)
    {
        if ($recordUpdateInfo) {
            parent::beforeUpdate();
        } else {
            $this->beforeUpdate();
        }
        return parent::save($data, $whiteList);
    }

    public function beforeUpdate()
    {
        return true;
    }



    /**
     * Allows to query a set of records that match the specified conditions
     *
     * @param mixed $parameters
     * @return XhhrmStaff[]|XhhrmStaff
     */
    public static function find($parameters = null)
    {
        return parent::find($parameters);
    }

    /**
     * Allows to query the first record that match the specified conditions
     *
     * @param mixed $parameters
     * @return XhhrmStaff
     */
    public static function findFirst($parameters = null)
    {
        return parent::findFirst($parameters);
    }

    /**
     * 部门人员树
     * @param $id
     * @param bool $arrReturn
     * @param bool $onlyData 只要数据
     * @return array|string
     * created by dale 2017/10/18
     */
    public static function getDepStaff($id,$arrReturn=false,$onlyData=false, $withPhone = false){
        $data=self::recursion($id, $onlyData, $withPhone);
        if($arrReturn){
            return $data;
        }else{
            return json_encode($data);
        }
    }

    /**
     * 根据部门标签,获取子部门下的树
     * @param $tag
     * @param bool $arrReturn
     * @param bool $onlyData
     * @return array|string
     * created by dale 2017/11/8
     */
    public static function getDepStaffByTag($tag,$arrReturn=false,$onlyData=false){
        $tag   = strtoupper($tag);//转大写
        if($tag == "ALL"){
            $id = 0;
        }else{
            $obj = XhhrmDepart::findFirst([
                'columns'    => 'iDepId',
                'conditions' => "bDelete=:bDelete: AND sTag=:sTag:",
                'bind'      => array('sTag' =>$tag , 'bDelete' => 0),
            ]);
            if(!$obj){
                die('没找到该部门标签');
            }
            $id = $obj->iDepId;
        }

        $data=self::recursion($id,$onlyData);
        if($arrReturn){
            return $data;
        }else{
            return json_encode($data);
        }
    }




    /**
     * 获取
     * @param $parentId  父部门id
     * @param $onlyData  只获取staff数据
     * @return array
     * created by dale 2017/10/18
     * modify by dale 20190219
     */
    public static function recursion($parentId, $onlyData, $withPhone = false)
    {  //获取Staff信息
        $parameters = array(
            'conditions' => "bDelete=:bDelete: AND iParentId=:parentId: ",
            'bind' => array('parentId' =>$parentId , 'bDelete' => 0),
        );
        $objs=XhhrmDepart::find($parameters);  //当前传入部门id 为父部门的子部门
        if($objs->toArray()==[]){ //如果子部门为空,没有子部门
            $staffs = self::find([
                'columns'=>'iUserId,sStaffName,sDepIds,sChargeDeps,sSelfPhone',
                'conditions'=>'bDelete=0 AND sDepIds like :key: AND iStaffStatus=1 AND iUserId is not null',
                'bind'      => ['key'=>'%,'.$parentId.',%'],
            ]);
            $staffs=$staffs->toArray();
            $staffArr=[];
            foreach ($staffs as $staff){
                $item=[];
                $item['id']=$staff['iUserId'];
                $item['text']=$staff['sStaffName'];
                if ($withPhone  && $staff['sSelfPhone']) {
                    $item['text'] .= "({$staff['sSelfPhone']})";
                }
                if(!$onlyData){
                    $item['iconCls'] = 'fa fa-user';
                    if($staff['sChargeDeps'] != null && $staff['sChargeDeps'] != ''){
                        $item['iconCls'] .= ' fa-manager-color';
                    }
                }
                $staffArr[]=$item;
            }
            return $staffArr;
        }


        $array=$objs->toArray(); //子部门
        $newArray=[];
        $conditionArr=[];
        foreach ($array as $key=>$value){

            $newArray[$key]['id']='D-'.$value['iDepId'];
            $newArray[$key]['text']=$value['sDepName'];
            if(!$onlyData){
                $newArray[$key]['iconCls']='fa fa-group';
            }
            $newArray[$key]['children']=self::recursion($value['iDepId'],$onlyData, $withPhone);
            if(!$onlyData){
                if($newArray[$key]['children']){
                    $newArray[$key]['state']="closed";
                }
            }
            $conditionArr[]="sDepIds not like '%,".$value['iDepId'].",%' ";
        }
        $conditionArr=implode(' AND ',$conditionArr);
        $conditionArr='( '.$conditionArr.' )';
        if ($parentId) {
            $staffs=self::find([
                'columns'=>'iUserId,sStaffName,sDepIds,sChargeDeps,sSelfPhone',
                'conditions'=>"bDelete=0 AND iStaffStatus=1 AND sDepIds like :key: AND iUserId is not null AND  ".$conditionArr,
                'bind'      => ['key'=>'%,'.$parentId.',%'],
            ])->toArray();
        } else { //parentId = 0;
            $staffs=self::find([
                'columns'=>'iUserId,sStaffName,sDepIds,sChargeDeps,sSelfPhone',
                'conditions'=>"bDelete=0 AND iStaffStatus=1 AND sDepIds is null   AND iUserId is not null  ",
            ])->toArray();
        }
        if($staffs!=[]){
            foreach ($staffs as $staff){
                $item=[];
                $item['id']=$staff['iUserId'];
                $item['text']=$staff['sStaffName'];
                if ($withPhone && $staff['sSelfPhone']) {
                    $item['text'] .= "({$staff['sSelfPhone']})";
                }
                if(!$onlyData){
                    $item['iconCls']='fa fa-user';
                    if($staff['sChargeDeps'] != null && $staff['sChargeDeps'] != ''){
                        $item['iconCls'] .= ' fa-manager-color';
                    }
                }
                $newArray[]=$item;
            }
        }
        return $newArray;
    }

    /**
     * 根据传入的id数组获取staffNameArr
     * @param $idArr
     * @return XhhrmStaff|XhhrmStaff[]|array|bool
     * created by dale 2017119
     */
    public static function getStaffNameById($idArr)
    {
        if(!$idArr) return false;
        $staffInfo = self::find([
            'columns'    => 'iUserId,sStaffName',
            'conditions' => 'iUserId IN ({idArr:array})',
            'bind'       => ['idArr' => $idArr]
        ]);
        if(!$staffInfo) return [];
        $staffInfo = array_column($staffInfo->toArray(), 'sStaffName', 'iUserId');
        return $staffInfo;
    }

    /**
     * 根据传入的userId数组获取部门的
     *
     * @param $idArr
     * @return XhhrmStaff|XhhrmStaff[]|array|bool
     * created by dale 2017/11/18
     */
    public static function getPhoneById($idArr)
    {
        if(!$idArr) return false;
        $staffInfo = self::find([
            'columns'    => 'iUserId,sSelfPhone',
            'conditions' => 'iUserId IN ({idArr:array})',
            'bind'       => ['idArr' => $idArr]
        ]);
        if(!$staffInfo) return [];
        $staffInfo = array_column($staffInfo->toArray(), 'sSelfPhone', 'iUserId');
        return $staffInfo;
    }

    /**
     * 获取员工
     *
     * @return array
     *
     * create by dale  20180716
     */
    public static function getStaff()
    {
        $staff = self::find([
            'columns'    => 'iUserId, sStaffName',
            'conditions' => 'bDelete = 0 and iStaffStatus = 1 and iUserId is not null'
        ])->toArray();
        return array_column($staff, 'sStaffName', 'iUserId');
    }


//    --------------------------------------------newFunction-------------------------------------------------------------------

    /**
     * 记录日志
     *
     * @param $function
     * @param $data
     * @param $detail
     * @param $msg
     *
     * @return bool
     *
     * create by dale  20181219
     */
    public static function parseLog($function, $data, $detail, $msg)
    {
        return Main::createCommitLog(
            'hrm',
            'staff_model',
            $function,
            ['post' => $data, 'get' => [], 'detail' => $detail],
            null,
            $msg
        );
    }


    public static $enums = [
        'iEmploySource' => [1 => '网站投递', 2 => '猎头推荐', 3 => '招聘会', 4 => '内部员工推荐'],
        'bMarried' => [1 => '已', 0 => '未'],
        'iWorkStatus' => [
            1 => '兼职',
            2 => '实习',
            3 => '全职',
            4 => '应届',
        ],
        'iStaffStatus' => [
            1 => '在职',
            2 => '离职',
            3 => '退休',
        ],
        'iOfferStatus' => [
            1 => '试用',
            2 => '正式',
            3 => '非正式',
            4 => '其他'
        ],
        'iUserSex' => [1 => '男', 2 => '女'],
        'mSuggest' => ['复试', '条件尚可但暂不考虑,可纳入后备人才库', '不予以考虑', '试用', '变更岗位试用'],
//        'iRegisterType' => [1 => '本地城镇', 2 => '本地农村', 3 => '外地城镇', 4 => '外地农村' ],
        'iRegisterType' => [
            10 => '本地城镇（主城区）',
            11 => '外地城镇（省内市外）',
            12 => '外地城镇（省外）',
            20 => '本地农村（主城区）',
            21 => '外地农村（省内市外）',
            22 => '外地农村（省外）',
        ],

    ];

    /**
     * 导入职工
     *
     * @param $filePath
     *
     * @return array
     * @throws \Exception
     *
     * create by dale  20181218
     */
    public static function importStaff($filePath)
    {
        if (!file_exists($filePath)) {
            throw new \Exception('文件不存在');
        }
        ini_set('memory_limit', '500M');
        $dataSource = Excel::read($filePath, 1);
        $newData = self::dealExcelData($dataSource, self::$convertTitleArr);
        unset($dataSource);
        $dataSource = Excel::read($filePath, 3);
        $newData = array_merge($newData, self::dealExcelData($dataSource, self::$convertTitleArr));
        unset($dataSource);
//        var_dump($newData);die;
        $errorNum = 0;
        $successNum = 0;
        $totalNum = count($newData);
        $errorArr = [];
        foreach ($newData as $row) {
            try {
                Di::getDefault()->get('db')->begin();
                $staffName = Tool::getValue($row, 'sStaffName', '');
                $identityCode = Tool::getValue($row, 'sIdentityCode', '');
                if (!$staffName || !$identityCode) {
                    throw new \Exception('缺少职工唯一标识');
                }
                $staffCount = XhhrmStaff::count([
                    'conditions' => 'bDelete = 0 and sStaffName = :sStaffName: and sIdentityCode = :sIdentityCode:',
                    'bind'       => ['sStaffName' => $staffName, 'sIdentityCode' => $identityCode]
                ]);
                if (!$staffCount) {
                    self::addStaff($row, 'staff_import', false);
                } elseif ($staffCount == 1) {
                    self::modifyStaff($row);
                } else {
                    throw new \Exception('存在该职工信息大于2');
                }
                $successNum++;
                Di::getDefault()->get('db')->commit();
            } catch (\Exception $e) {
                Di::getDefault()->get('db')->rollback();
                $row['errorLog'] = $e->getMessage();
                $errorArr [] = $row;
                $errorNum++;
            }
        }
        return [
            'totalNum' => $totalNum,
            'errorNum' => $errorNum,
            'successNum' => $successNum,
            'errorArr' => $errorArr,
        ];
    }

    /**
     * 导入离职职工信息
     * @param $filePath
     *
     * @return array
     * @throws \Exception
     *
     * create by dale  20190221
     */
    public static function importLeaveStaff($filePath)
    {
        if (!file_exists($filePath)) {
            throw new \Exception('文件不存在');
        }
        ini_set('memory_limit', '500M');
        $dataSource = Excel::read($filePath, 2);
        $title = self::$convertTitleArr;
        $title['tLeaveTime'] = '离职日期';
        $title['sLeaveReason'] = '离职原因';
        $newData = self::dealExcelData($dataSource, $title);
        unset($dataSource);
        $dataSource = Excel::read($filePath, 4);
        $newData = array_merge($newData, self::dealExcelData($dataSource, $title));
        unset($dataSource);
        $errorNum = 0;
        $successNum = 0;
        $totalNum = count($newData);
        $errorArr = [];
        foreach ($newData as $row) {
            try {
                Di::getDefault()->get('db')->begin();
                $staffName = Tool::getValue($row, 'sStaffName', '');
                $identityCode = Tool::getValue($row, 'sIdentityCode', '');
                if (!$staffName || !$identityCode) {
                    throw new \Exception('缺少职工唯一标识');
                }
                $staffCount = XhhrmStaff::count([
                    'conditions' => 'bDelete = 0 and sStaffName = :sStaffName: and sIdentityCode = :sIdentityCode:',
                    'bind'       => ['sStaffName' => $staffName, 'sIdentityCode' => $identityCode]
                ]);
                if (!$staffCount) {
                    $obj = new XhhrmStaff();
                    if (!$row['sIdentityCode'] || !$row['sStaffName'] || !$row['sSelfPhone']) {
                        throw new \Exception('职工姓名，电话，身份证必填');
                    }
                    if (!self::checkIdentityCode($row['sIdentityCode'])) {
                        throw new \Exception('职工身份证重复');
                    }
                    $obj->assign($row);
                    $obj->iStaffStatus = 2;
                    if (!$obj->save()) {
                        throw new \Exception('离职职工信息新增失败');
                    }
                    $successNum++;
                } elseif ($staffCount == 1) {
                    if ($row['sIdentityCode'] && $row['sStaffName']) {
                        $obj = XhhrmStaff::findFirst([
                            'conditions' => 'bDelete = 0 and sStaffName = :sStaffName: and sIdentityCode = :sIdentityCode:',
                            'bind'       => ['sStaffName' => $row['sStaffName'], 'sIdentityCode' => $row['sIdentityCode']]
                        ]);
                    } else {
                        throw new \Exception('缺少职工唯一标识,无法编辑职工数据');
                    }
                    if (!self::checkIdentityCode($row['sIdentityCode'], $obj->iStaffId)) {
                        throw new \Exception('职工身份证重复');
                    }
                    $obj->assign($row);
                    $obj->iStaffStatus = 2;
                    if (!$obj->save()) {
                        throw new \Exception('离职职工信息编辑失败');
                    }
                    $successNum++;
                } else {
                    throw new \Exception('存在该职工信息大于2');
                }
                Di::getDefault()->get('db')->commit();
            } catch (\Exception $e) {
                Di::getDefault()->get('db')->rollback();
                $row['errorLog'] = $e->getMessage();
                $errorArr [] = $row;
                $errorNum++;
            }
        }
        return [
            'totalNum' => $totalNum,
            'errorNum' => $errorNum,
            'successNum' => $successNum,
            'errorArr' => $errorArr,
        ];
    }

    /**
     * 处理excel信息
     *
     * @param $dataSource
     *
     * @return array
     * @throws \Exception
     *
     * create by dale  20190220
     */
    public static function dealExcelData(&$dataSource, $convertTitleArr)
    {
        if (!$convertTitleArr) {
            throw new \Exception('缺少参数');
        }
        $indexTitleArr = @$dataSource[0];
        unset($dataSource[0]);
        $indexTitleArr = array_filter($indexTitleArr);
        //标题去空格
        $indexTitleArr = array_map(function ($val) {
            $index = mb_strpos($val, '（');
            if ($index !== false) {
                $val = mb_substr($val, 0, $index);
            }
            if (mb_strpos($val, '公积金缴存基数') !== false) {
                return '公积金缴存基数';
            }
            return trim($val);
        }, $indexTitleArr);
//        var_dump($indexTitleArr);die;
        $data = @$dataSource;
        $data = array_filter(
            $data,
            function ($val) {
                for ($i= 0; $i <= 10; $i++) { //取10行看看值存在不
                    if ($val[$i]) {
                        return true;
                    }
                }
            }
        );
        unset($dataSource);
        $convertTitleArr = array_filter(array_flip($convertTitleArr)); //键值对反转
        $filedIndexArr = []; //字段和index对应关系数组
        foreach ($indexTitleArr as $index => $title) {
            $field = Tool::getValue($convertTitleArr, $title, null);
            if ($field) {
                $filedIndexArr[$field] = $index;
            }
        }
        unset($convertTitleArr);
        unset($indexTitleArr);
        if (!$filedIndexArr) {
            throw new \Exception('excel格式不对');
        }

        $filedArr = array_flip($filedIndexArr); // index => $filed
        $needKeys = array_keys($filedArr);
        $newData = [];
        foreach ($data as $index => $row) {
            $arr = [];
            foreach ($row as $key => $value) {
                if (in_array($key, $needKeys)) {
                    $arr[$filedArr[$key]] = $value;
                }
            }
            unset($data[$index]);
            $arr = array_filter($arr);
            foreach ($arr as $key => $value) {
                if (!$value || $value == '——') {
                    $arr[$key] = '';
                    continue;
                }
                if (in_array($key, ['tHireDate', 'tRegularDate'])) {
                    $arr[$key] = date('Y-m-d', strtotime($value));
                }
//                if (in_array($key, ['tSocialPayDate', 'sSurplusPayDate', 'sInsuranceDate'])) {
//                    if ($value &&  strlen($value) == 6) {
//                        $arr[$key] = mb_substr($value, 0, 4).'-'.mb_substr($value, 4, 2).'-01';
//                    }
//                }
                if ($key == 'iOfferStatus') {
                    if ($value == '正式员工') {
                        $arr[$key] = 2;
                    } elseif ($value == '非正式员工') {
                        $arr[$key] = 3;
                    } elseif ($value == '其他') {
                        $arr[$key] = 4;
                    }
                }
                if ($key == 'iWorkStatus') {
                    if ($value == '实习生') {
                        $arr[$key] = 2;
                    } elseif ($value == '员工分组') {
                        $arr[$key] = 0;
                    } elseif ($value == '兼职') {
                        $arr[$key] = 1;
                    }
                }
                if ($key == 'tStartWork') { //开始工作时间
                    $value = trim($value);
                    $endFix = mb_substr($value, -1); //判断最后一个字符是年还是月
                    if ($endFix == '月') {
                        $year  = mb_substr($value, 0, 4);
                        $month = mb_substr($value, 5, 2);
                        if (mb_substr($month, -1) == '月') {
                            $month = '0'.mb_substr($month, 0, 1);
                        }
                        $arr[$key] = date('Y-m-d', strtotime("{$year}-{$month}-01"));
                    } elseif ($endFix == '年') {
                        $year  = mb_substr($value, 0, 4);
                        $arr[$key] = date('Y-m-d', strtotime("{$year}-01-20"));
                    } else {
                        unset($arr[$key]);
                    }
                }
                if (in_array($key, [
                    'iUserSex','bMarried','iRegisterType'
                ])) {
                    if ($value) {
                        foreach (self::$enums[$key] as $register => $name) { //键值
                            if (strpos($value, $name) !== false) {
                                $arr[$key] = $register;
                            }
                        }
                    }
                }
            }
            if (@$arr['sIdentityCode']) {
                $arr['tBirthday'] = self::getBirthdayBysIdentityCode(@$arr['sIdentityCode']);
            }
            $newData[] = $arr;
            unset($arr);
            unset($data[$index]);
        }
        return $newData;
    }

    /**
     * 根据身份证号号码获取出生年月
     *
     * @param string $sIdentityCode
     *
     * @return bool|string
     *
     * create by dale  20190219
     */
    public static function getBirthdayBysIdentityCode($sIdentityCode = '330621199512060835')
    {
        if (!$sIdentityCode) {
            return '';
        }
        $birthday = strlen($sIdentityCode) == 15 ? ('19' . substr($sIdentityCode, 6, 6)) :
            substr($sIdentityCode, 6, 8);
        return substr($birthday, 0, 4) .'-'.substr($birthday, 4, 2).'-'.
            substr($birthday, 6, 2);
    }

    /**
     * 验证身份证号是否存在
     *
     * @param $identityCode
     * @param null $staffId
     *
     * @return bool
     *
     * create by dale  20181218
     */
    public static function checkIdentityCode($identityCode, $staffId = null)
    {
        $staffArr = XhhrmStaff::find([
            'conditions' => 'bDelete = 0 and sIdentityCode = :sIdentityCode: ',
            'bind'        => ['sIdentityCode' => $identityCode]
        ])->toArray();
        if (!$staffArr) {
            return true;
        }
        if (count($staffArr) == 1 && $staffId == $staffArr[0]['iStaffId']) {
            return true;
        }
        if (count($staffArr) > 1) {
            return false;
        }
        return false;
    }


    /**
     * 新增职工
     *
     * @param $data
     * @param string $createMode
     * @param bool $createMail
     * @param null $whiteList
     *
     * @return bool
     * @throws \Exception
     *
     * create by dale  20181218
     */
    public static function addStaff($data, $createMode = 'staff_save', $createMail = true, $whiteList = null)
    {
        $obj = new XhhrmStaff();
        if (!$data['sIdentityCode'] || !$data['sStaffName'] || !$data['sSelfPhone']) {
            throw new \Exception('职工姓名，电话，身份证必填');
        }
        if (!self::checkIdentityCode($data['sIdentityCode'])) {
            throw new \Exception('职工身份证重复');
        }
        $obj->assign($data, null, $whiteList);
        $obj->sCreateMode = $createMode;
        $obj->iStaffStatus = 1;
        if (!$obj->save()) {
            throw new \Exception('职工信息新增失败');
        }
        $check = XhsysUser::findFirst([
            'conditions' => 'bDelete = 0 and sUserName = :sUserName: and sSelfPhone = :sSelfPhone: ',
            'bind'       => ['sUserName' => $obj->sStaffName, 'sSelfPhone' => $obj->sSelfPhone]
        ]);
        if (!$check) {
            self::createStaffUser($obj->sStaffName, $obj->sSelfPhone);
        }
        $user = XhsysUser::findFirst([
            'conditions' => 'bDelete = 0 and sUserName = :sUserName: and sSelfPhone = :sSelfPhone: ',
            'bind'       => ['sUserName' => $obj->sStaffName, 'sSelfPhone' => $obj->sSelfPhone]
        ]);
        if ($user) {
            $obj->iUserId = $user->iUserId;
            if (!$obj->save()) {
                throw new \Exception('职工账号更新失败');
            }
        }
        if ($createMail) {
            try {
                self::createHundredMail($obj->iStaffId);
            } catch (\Exception $e) {
                self::parseLog('modifyStaff', $data, '邮箱创建失败:'.$e->getMessage(), $e->getMessage());
                return true;
            }
        }
        return true;
    }


    /**
     * 修改职工信息
     *
     * @param $data
     * @param null $whiteList
     * @param bool $recordUpdateInfo
     *
     * @return bool
     * @throws \Exception
     *
     * create by dale  20181218
     */
    public static function modifyStaff($data, $whiteList = null, $recordUpdateInfo = true)
    {
        $staffId = Tool::getValue($data, 'iStaffId', 0);
        $staffName = Tool::getValue($data, 'sStaffName', '');
        $identityCode = Tool::getValue($data, 'sIdentityCode', '');
        if ($staffId) {
            $obj = XhhrmStaff::findFirst($staffId);
        } elseif ($staffName && $identityCode) {
            $obj = XhhrmStaff::findFirst([
                'conditions' => 'bDelete = 0 and sStaffName = :sStaffName: and sIdentityCode = :sIdentityCode:',
                'bind'       => ['sStaffName' => $staffName, 'sIdentityCode' => $identityCode]
            ]);
        } else {
            throw new \Exception('缺少职工唯一标识,无法编辑职工数据');
        }
        if (!self::checkIdentityCode($data['sIdentityCode'], $obj->iStaffId)) {
            throw new \Exception('职工身份证重复');
        }
        $obj->assign($data);
        $changeFields = $obj->getChangedFields();
        if (!$obj->save(null, $whiteList, $recordUpdateInfo)) {
            throw new \Exception('职工信息编辑保存失败');
        }
        if ($obj->iUserId) {
            $user = XhsysUser::findFirst($obj->iUserId);
            if ($user) {
                if (in_array('sStaffName', $changeFields)) {
                    $user->sUserName = $obj->sStaffName;
                }
                if (in_array('sSelfPhone', $changeFields)) {
                    $user->sSelfPhone = $obj->sSelfPhone;
                }
                if (!$user->save()) {
                    throw new \Exception('职工姓名,职工电话更新到user失败');
                }
            }
        }
        if (in_array('sHundredMail', $changeFields)) { //邮箱变更时，处理邮箱
            try {
                self::createHundredMail($obj->iStaffId, $obj->sHundredMail);
            } catch (\Exception $e) {
                self::parseLog('modifyStaff', $data, '邮箱创建失败:'.$e->getMessage(), $e->getMessage());
                return true;
            }
        }
        return true;
    }

    /**
     * 计算年龄
     *
     * @param $birthday
     *
     * @return int
     *
     * create by dale  20181219
     */
    public static function calculateAge($birthday)
    {
        @list($year, $month, $day) = explode("-", $birthday);
        $year_diff = date("Y") - $year;
        $month_diff = date("m") - $month;
        $day_diff = date("d") - $day;
        if ($day_diff < 0 || $month_diff < 0) {
            $year_diff--;
        }
        return $year_diff < 0 ? 0 : $year_diff;
    }

    /**
     * 创建百分邮箱
     *
     * @param $staffId
     * @param string $email
     * @param string $password
     *
     * @return bool
     * @throws \Exception
     * @throws \Helpers\XhException
     *
     * create by dale  20181219
     */
    public static function createHundredMail($staffId, $email = '', $password = 'xuehai1234')
    {
        if (!$staffId) {
            throw new \Exception('缺少职工id');
        }
        $staff = XhhrmStaff::findFirst($staffId);
        if (!$staff) {
            throw new \Exception('未找到职工记录');
        }
        if (!$email) {
            if (!$staff->sSelfPhone) {
                throw new \Exception('未填写职工电话，无法通过电话创建邮箱');
            }
            $email = $staff->sSelfPhone.'@100fen.cn';
        }
        $res = HundredMail::checkMail($email);
        if (!$res) {
            HundredMail::addMail($email, $staff->sStaffName, $staff->sSelfPhone, $password);
        }
        $staff->sHundredMail = $email;
        if (!$staff->save()) {
            throw new \Exception('职工邮箱保存失败');
        }
        return true;
    }



    /**
     * 创建职工账号
     *
     * @param $staffName
     * @param $phoneNum
     * @param string $pwd
     *
     * @return bool
     * @throws \Exception
     *
     * create by dale  20181218
     */
    public static function createStaffUser($staffName, $phoneNum, $pwd = '123456')
    {
        $user = new XhsysUser();
        $user->sLogonName   = $phoneNum;
        $user->sUserName    = $staffName;
        $user->sLogonPwd    = strtoupper(md5($pwd));
        $user->sSelfPhone   = $phoneNum;
        $user->iUserType    = 5;
        $user->iSchoolId    = 1;
        $user->bCompany     = 1;
        return $user->insertAfterOld();
    }


    /**
     * 获取单个职工信息
     *
     * @param $staffId
     * @param null $whitList
     *
     * @return mixed
     * @throws \Exception
     *
     * create by dale  20181219
     */
    public static function getStaffInfo($staffId, $whitList = null)
    {
        if (!$staffId) {
            throw new \Exception('缺少职工id');
        }
        $staffColumns =  array_keys(get_object_vars(new XhhrmStaff()));
        //去除私有对象
        $staffColumns = array_filter(array_map(function ($val) {
            if (strpos($val, '_') !== false) {
                return '';
            } else {
                return $val;
            }
        }, $staffColumns));
        if ($whitList) {
            $staffColumns = array_intersect($staffColumns, $whitList);
        }
        $staffColumns = array_map(function ($val) {
            return 's.'.$val;
        }, $staffColumns);
        $builder =  Di::getDefault()->get('modelsManager')->createBuilder()
            ->from(['s' => 'Admin\Models\hrm\XhhrmStaff'])
            ->columns(array_merge($staffColumns, []))
            ->where('s.bDelete = 0 and s.iStaffId = :iStaffId:', ['iStaffId' => $staffId])
            ->limit(1);
        $info = $builder->getQuery()->execute()->toArray();
        if (!Tool::getValue($info, 0)) {
            throw new \Exception('未找到该职工的信息');
        }
        self::runStaffTime($info, true);
        XhhrmStaff::runAgeByTime($info, ['tBirthday' => 'iAge', 'tHireDate' => 'sCompanyYear']);//计算年龄
        XhhrmDepart::runDepNameByDepId($info, ['sDepIds' => 'sDepName']); //部门
        Tool::runEnum($info, [
            'bMarried' => [0 => '', 1 => '是', 0 => '否'],
            'iWorkStatus' => [
                0 => '',
                1 => '兼职',
                2 => '实习',
                3 => '全职',
            ],
            'iStaffStatus' => [
                0 => '',
                1 => '在职',
                2 => '离职',
                3 => '退休',
            ],
            'iOfferStatus' => [
                0 => '',
                1 => '试用',
                2 => '正式'
            ],
            'iUserSex' => [0 => '', '1' => '男', 2 => '女'],
            'bInHoliday' => [0 => '否', 1 => '是']
        ]);
        $info = @$info[0];
        if (!$info) {
            throw new \Exception('未找到该职工的信息');
        }
        return $info;
    }


    /**
     * 改变职工状态
     *
     * @param $ids
     * @param $field
     * @param $value
     * @param string $date
     * @param string $reason
     *
     * @return bool
     * @throws \Exception
     *
     * create by dale  20181221
     * modify by dale 20190221  $reason
     */
    public static function changeStaffStatus($ids, $field, $value, $date = '', $reason = '')
    {
        if (is_string($ids)) {
            $ids = explode(',', $ids);
        }
        if (!is_array($ids) || !$field) {
            throw new \Exception('缺少参数');
        }
        $date = $date ? $date : date('Y-m-d');
        $staffs = XhhrmStaff::find([
            'conditions' => 'bDelete=0 AND iStaffId in ({ids:array})',
            'bind' => ['ids' => $ids],
        ]);
        $userIds = [];
        foreach ($staffs as $staff) {
            if ($staff->iUserId != null) {
                $userIds[] = $staff->iUserId;
            }
            $staff->$field = $value;
            if ($field == 'iStaffStatus') {
                switch ($value) {
                    case 1:
                        $staff->tHireDate = $date;
                        break;
                    case 2:
                        $staff->tLeaveTime = $date;
                        if ($reason) {
                            $staff->sLeaveReason = $reason;
                        }
                        break;
                    case 3:
                        $staff->tRetireTime = $date;
                        break;
                    default:
                        break;
                }
            }
            if ($staff->mHistory == null) {
                $staff->mHistory = json_encode([
                    [
                        'time' => $date ,
                        'type' => $field,
                        'status' => $value,
                        'operator' => Main::getLoginUserInfo('userId'),
                        'operateTime' => date("Y-m-d H:i:s", time())
                    ]
                ], JSON_UNESCAPED_UNICODE);
            } else {
                $arr = json_decode($staff->mHistory, true);
                $arr[] = [
                    'time' => $date,
                    'type' => $field,
                    'status' => $value,
                    'operator' => Main::getLoginUserInfo('userId'),
                    'operateTime' => date("Y-m-d H:i:s", time())
                ];
                $staff->mHistory = json_encode($arr, JSON_UNESCAPED_UNICODE);
            }
            if (!$staff->save()) {
                throw new \Exception('保存失败');
            }
        }
        if ($field == 'iStaffStatus') { //职工状态变更
            $users = XhsysUser::find([
                'conditions' => 'bDelete=0 AND iUserId in ({ids:array})',
                'bind' => ['ids' => $userIds],
            ]);
            if ($value == 1) { //在职
                foreach ($users as $user) {
                    $user->bDisable = 0;
                    if (!$user->save()) {
                        throw new \Exception('修改账号状态为启用');
                    }
                }
            } elseif ($value == 2) { //离职
                foreach ($users as $user) {
                    $user->bDisable = 1;
                    if (!$user->save()) {
                        throw new \Exception('修改账号状态为禁用');
                    }
                }
            }
        }
        return true;
    }

    /**
     * 获取职工列表
     *
     * @param array $params
     * @param bool $isPageBuilder
     *
     * @return array
     *
     * create by dale  20181224
     */
    public static function getStaffList($params = [], $isPageBuilder = true)
    {
        $fields = Tool::getValue($params, 'fields', []);
        $workStatus = Tool::getValue($params, 'workStatus');
        $staffStatus = Tool::getValue($params, 'staffStatus');
        $offerStatus = Tool::getValue($params, 'offerStatus');
        $depId = Tool::getValue($params, 'depId');
        $key = Tool::getValue($params, 'key');
        $bManager = Tool::getValue($params, 'bManager');
        $bOffWork = Tool::getValue($params, 'bOffWork');
        $staffIds = Tool::getValue($params, 'staffIds');
        $special = Tool::getValue($params, 'special');
        $sort = Tool::getValue($params, 'sort');
        $order = Tool::getValue($params, 'order');
        $staffColumns =  array_keys(get_object_vars(new XhhrmStaff()));
        //去除私有对象
        $staffColumns = array_filter(array_map(function ($val) {
            if (strpos($val, '_') !== false) {
                return '';
            } else {
                return $val;
            }
        }, $staffColumns));
        if ($fields) {
            $staffColumns = array_intersect($staffColumns, $fields);
        }
        $staffColumns = array_map(function ($val) {
            return 's.'.$val;
        }, $staffColumns);
        $builder =  Di::getDefault()->get('modelsManager')->createBuilder()
            ->from(['s' => 'Admin\Models\hrm\XhhrmStaff'])
            ->leftJoin('Admin\Models\user\XhsysUser', 'u.iUserId=s.iUserId', 'u')
            ->columns(array_merge($staffColumns, ['u.iUserId','u.bDisable']))
            ->where('s.bDelete = 0');
        if ($bManager == 2) {
            $builder->andWhere('sChargeDeps is not null');
        }
        if ($key != null) {
            $builder->andWhere('s.sStaffName like :key: OR s.sSelfPhone like :key: OR s.sHundredMail like :key: 
                OR s.sStaffNumber like :key: OR s.sIdentityCode like :key: ', array('key' => '%' . $key . '%'));
        };
        if ($depId) {
            $builder->andWhere('s.sDepIds LIKE :sDepIds:', array('sDepIds' => '%,' . $depId . ',%'));
        }
        if ($workStatus) {
            $builder->andWhere('s.iWorkStatus=:iWorkStatus:', array('iWorkStatus' => $workStatus));
        }
        if ($staffStatus) {
            $builder->andWhere('s.iStaffStatus=:iStaffStatus:', array('iStaffStatus' => $staffStatus));
        }
        if ($offerStatus) {
            $builder->andWhere('s.iOfferStatus=:iOfferStatus:', array('iOfferStatus' => $offerStatus));
        }
        if ($bOffWork) {
            $builder->andWhere('iStaffStatus != 2');
        }
        if ($staffIds) {
            $builder->andWhere('s.iStaffId in ({ids:array})', ['ids' => $staffIds]);
        }
        if ($special) {
            $builder->andWhere('s.bSpecial = :special:', ['special' => $special]);
        }
        if ($order && $sort) {
            $builder->orderBy(" s.{$sort} {$order} ");
        }
        if ($isPageBuilder) {
            $data = Main::runBuilderPage($builder);
            XhhrmStaff::runStaffTime($data['rows'], true); //日期处理
            XhhrmStaff::runAgeByTime($data['rows'], ['tBirthday' => 'iAge', 'tHireDate' => 'sCompanyYear']);//计算年龄
            XhhrmDepart::runDepNameByDepId($data['rows'], ['sDepIds' => 'sDepName']); //部门
            Tool::runEnum($data['rows'], self::$enums);
            return $data;
        } else {
            $data = $builder->getQuery()->execute()->toArray();
            XhhrmStaff::runStaffTime($data, true); //日期处理
            XhhrmStaff::runAgeByTime($data, ['tBirthday' => 'iAge', 'tHireDate' => 'sCompanyYear']);//计算年龄
            XhhrmDepart::runDepNameByDepId($data, ['sDepIds' => 'sDepName']); //部门
            Tool::runEnum($data, self::$enums);
            return $data;
        }
    }

    /**
     * 计算年龄
     *
     * @param $obj
     * @param $fields
     * @param bool $isArray
     *
     * create by dale  20181224
     */
    public static function runAgeByTime(&$obj, $fields, $isArray = true)
    {
        is_string($fields) and $fields = [$fields => $fields];
        if ($isArray) {
            foreach ($obj as $index => $objOne) {
                foreach ($fields as $idField => $nameField) {
                    $time = Tool::getValue($objOne, $idField);
                    if (!$time) {
                        continue;
                    }
                    $obj[$index][$nameField] = XhhrmStaff::calculateAge($time);
                }
            }
        } else {
            foreach ($fields as $idField => $nameField) {
                $time = Tool::getValue($obj, $idField);
                if (!$time) {
                    continue;
                }
                $obj[$nameField] = XhhrmStaff::calculateAge($time);
            }
        }
    }

    /**
     * 处理职工时间类型
     *
     * @param $obj
     * @param bool $isArray
     *
     * create by dale  20181219
     */
    private static function runStaffTime(&$obj, $isArray = true)
    {
        if ($isArray) {
            foreach ($obj as $index => $objOne) {
                $monthArr = ['tSocialPayDate', 'tStartWork', 'tGraduateDate'];
                foreach ($monthArr as $field) {
                    if (!array_key_exists($field, $objOne)) {
                        continue;
                    }
                    if ($objOne[$field] == '0000-00-00') {
                        $objOne[$field] = date('Y-m', strtotime(''));
                    } else {
                        $objOne[$field] = date('Y-m', strtotime($objOne[$field]));
                    }
                    $obj[$index][$field] = $objOne[$field] == '1970-01' ? '' :$objOne[$field];
                }
                $dateArr = ['tLeaveTime','tBirthday', 'tRetireTime'];
                foreach ($dateArr as $field) {
                    if (!array_key_exists($field, $objOne)) {
                        continue;
                    }
                    if ($objOne[$field] == '0000-00-00') {
                        $objOne[$field] = date('Y-m-d', strtotime(''));
                    } else {
                        $objOne[$field] = date('Y-m-d', strtotime($objOne[$field]));
                    }
                    $obj[$index][$field] = $objOne[$field] == '1970-01-01' ? '' :$objOne[$field];
                }
            }
        } else {
            $monthArr = ['tHireDate', 'tRegularDate', 'tSocialPayDate', 'tStartWork', 'tGraduateDate'];
            foreach ($monthArr as $field) {
                if (!array_key_exists($field, $obj)) {
                    continue;
                }
                if ($obj[$field] == '0000-00-00') {
                    $obj[$field] = date('Y-m', strtotime(''));
                } else {
                    $obj[$field] = date('Y-m', strtotime($obj[$field]));
                }
                $obj[$field] = $obj[$field] == '1970-01' ? '' :$obj[$field];
            }
            $dateArr = ['tLeaveTime','tBirthday', 'tRetireTime'];
            foreach ($dateArr as $field) {
                if (!array_key_exists($field, $obj)) {
                    continue;
                }
                if ($obj[$field] == '0000-00-00') {
                    $obj[$field] = date('Y-m-d', strtotime(''));
                } else {
                    $obj[$field] = date('Y-m-d', strtotime($obj[$field]));
                }
                $obj[$field] = $obj[$field] == '1970-01-01' ? '' :$obj[$field];
            }
        }
    }




}
